package com.twt.recruit.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twt.recruit.entity.*;
import com.twt.recruit.mapper.*;
import com.twt.recruit.service.ProjectService;
import com.twt.recruit.utils.JwtTokenUtils;
import com.twt.recruit.utils.TimeUtil;
import com.twt.recruit.utils.response.CommonEnum;
import com.twt.recruit.utils.response.ResultBody;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/v1")
public class MessageController {

    private final static Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Resource
    MessageMapper messageMapper;

    @Resource
    ClubMapper clubMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    ProjectMapper projectMapper;

    @Resource
    ProjectService projectService;

    @Resource
    ApplicationMapper applicationMapper;

    @Resource
    TimeHandMapper timeHandMapper;



    @PostMapping("/inter/message/send")
    @Operation(summary = "发送信息")
    public ResultBody sendMessage(@RequestParam Integer projectId,
                                  @RequestParam String title,
                                  @RequestParam List<Integer> userReceive,
                                  @RequestParam String content){
        try {
            for (Integer s : userReceive) {
                Message message = new Message();
                message.setProjectId(projectId);
                Project project = projectMapper.selectById(projectId);
                Application application = applicationMapper.selectById(s);

                int day = timeHandMapper.selectById(application.getApplicationId()).getDay();
                long t = project.getStartTime().getTime()+ ((long) day * 24 * 60 * 60 * 1000);

                //TODO:后面可以做短信模板，接云片
                message.setContent( content
                        .replace("{{userName}}", application.getApplicationName())
                        .replace("{{clubName}}", clubMapper.selectById(project.getClubId()).getName())
                        .replace("{{projectName}}", project.getTitle())
                        .replace("{{interviewTime}}", TimeUtil.timestampToDate(t, TimeUtil.Y_M_D)));
                message.setUserReceive(application.getApplicationUid());
                message.setIsReceive((byte)0);
                message.setTitle(title);
                messageMapper.insert(message);
            }
            return ResultBody.success("批量发送成功");
        }catch (Exception e){
            logger.error("发送信息失败", e);
            return ResultBody.error("发送信息失败");
        }

    }

    @PostMapping("/user/message/reply")
    @Operation(summary = "回复信息")
    public ResultBody replyMessage(@RequestParam Integer messageId,
                                  @RequestParam Integer isReceive,
                                  @RequestParam(defaultValue = "") String reply){
        try {
            LambdaUpdateWrapper<Message> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Message::getMessageId, messageId);
            updateWrapper.set(Message::getIsReceive, isReceive);
            updateWrapper.set(Message::getReply, reply);
            messageMapper.update(updateWrapper);
            return ResultBody.success(messageMapper.selectById(messageId));
        }catch (Exception e){
            logger.error("发送信息失败", e);
            return ResultBody.error("发送信息失败");
        }

    }

    @Operation(summary = "获取个人消息")
    @GetMapping("/user/messages")
    public ResultBody listMyMessages(@RequestHeader(JwtTokenUtils.TOKEN_HEADER) String token){
        try {
            String uid = JwtTokenUtils.getUserNumberHttp(token);
            LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Message::getUserReceive, uid);
            JSONArray re = new JSONArray();
            for (Message message : messageMapper.selectList(queryWrapper)) {
                Integer projectId = message.getProjectId();
                JSONObject t = JSONUtil.parseObj(message);
                Project p = projectMapper.selectById(projectId);
                Club club = clubMapper.selectById(p.getClubId());
                t.remove("projectId");
                t.remove("createdTime");
                t.remove("updatedTime");
                t.putOpt("createdTime", TimeUtil.timestampToDate(message.getCreatedTime().getTime(), TimeUtil.Y_M_D_H_M_S));
                t.putOpt("updatedTime", TimeUtil.timestampToDate(message.getUpdatedTime().getTime(), TimeUtil.Y_M_D_H_M_S));
                t.putOpt("clubId", club.getClubId());
                t.putOpt("clubName", club.getName());
                User user = userMapper.selectById(message.getUserReceive());
                t.putOpt("userName", user!=null?user.getName():"");
                t.putOpt("uid", user!=null?user.getUid():"");
                t.putOpt("telephone", user!=null?user.getTelephone():"");
                t.putOpt("clubAvatar", club.getAvatar());
                re.add(t);
            }
            return ResultBody.success(re);
        }catch (Exception e){
            logger.error("获取个人消息失败", e);
            return ResultBody.error("获取个人消息失败");
        }
    }

    @Operation(summary = "获取组织消息")
    @GetMapping("/staff/messages")
    public ResultBody listMyMessages(@RequestParam Integer projectId,
                                     @RequestParam(defaultValue = "1") Integer page,
                                     @RequestParam(defaultValue = "20") Integer pageSize,
                                     @RequestHeader(JwtTokenUtils.TOKEN_HEADER) String token){
        try {
            if (!projectService.isClubProject(projectId, JwtTokenUtils.getClubHttp(token))){
                return ResultBody.error(CommonEnum.PROJECT_VIRES);
            }
            Page<Message> rowPage = new Page<>(page, pageSize);
            LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Message::getProjectId, projectId);


            rowPage = messageMapper.selectPage(rowPage, queryWrapper);
            JSONObject re = JSONUtil.parseObj(rowPage);
            JSONArray records = new JSONArray();
            Project p = projectMapper.selectById(projectId);
            Club club = clubMapper.selectById(p.getClubId());
            for (Message message : rowPage.getRecords()) {
                JSONObject t = JSONUtil.parseObj(message);
                t.remove("projectId");
                t.remove("createdTime");
                t.remove("updatedTime");
                t.putOpt("createdTime", TimeUtil.timestampToDate(message.getCreatedTime().getTime(), TimeUtil.Y_M_D_H_M_S));
                t.putOpt("updatedTime", TimeUtil.timestampToDate(message.getUpdatedTime().getTime(), TimeUtil.Y_M_D_H_M_S));
                t.putOpt("clubId", club.getClubId());
                t.putOpt("clubName", club.getName());
                User user = userMapper.selectById(message.getUserReceive());
                t.putOpt("userName", user!=null?user.getName():"");
                t.putOpt("uid", user!=null?user.getUid():"");
                t.putOpt("telephone", user!=null?user.getTelephone():"");
                records.add(t);
            }
            re.putOpt("records", records);
            return ResultBody.success(re);
        }catch (Exception e){
            logger.error("获取个人消息失败", e);
            return ResultBody.error("获取个人消息失败");
        }
    }




}
